<template>
  <div>
    <el-table
      v-loading="loading"
      :data="roleList"
      ref="multipleRoleTable"
      border
      stripe
      @selection-change="handleSelectionChange"
      style="width: 100%"
    >
      <el-table-column type="selection" align="center" width="55"></el-table-column>
      <el-table-column prop="roleId" label="角色编号" align="center"></el-table-column>
      <el-table-column prop="roleName" label="角色名称" align="center"></el-table-column>
      <el-table-column prop="roleSort" label="排序码" align="center"></el-table-column>
      <el-table-column prop="remark" label="角色备注" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="{row}">
          <dict-tag :data-list="statusOptions" :value="row.status"></dict-tag>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: center;margin-top: 10px">
      <el-button type="primary" @click="saveUserRole">分配角色</el-button>
    </div>
  </div>
</template>

<script>
import sysRoleApi from "@/api/system/sysRole";

export default {
  name: "sys-user-select-role",
  props: {
    activeId: {
      type: Number,
      default: undefined
    }
  },
  watch: {
    activeId: {
      immediate: true,
      handler: function (newVal, oldVal) {

      }
    }
  },
  data() {
    return {
      loading: false,
      //角色状态的字典数据
      statusOptions: [],
      //角色数据
      roleList: [],
      //用户ID
      roleIds: []
    }
  },
  created() {
    this.getDataByType("sys_status_type").then(res => {
      this.statusOptions = res.data;
    })
    this.loading = true
    sysRoleApi.getAllRoles().then(res => {
      this.roleList = res.data;
      sysRoleApi.getRoleIdsByUserId(this.activeId).then(res2 => {
        let roleIds = res2.data;
        this.roleList.filter(role => {
          roleIds.filter(roleId => {
            if (role.roleId == roleId) {
              this.$refs.multipleRoleTable.toggleRowSelection(role);
            }
          })
        })
      })
      this.loading = false
    })

  },
  methods: {
    handleSelectionChange(val) {
      this.roleIds = []
      val.filter(role => {
        this.roleIds.push(role.roleId)
      })
    },
    //保存角色和用户的关系
    saveUserRole() {
      //得到用户ID
      let userId = this.activeId;
      console.log(userId)
      console.log(this.roleIds)
      sysRoleApi.saveUserRoles(userId, this.roleIds).then(res => {
        this.$message.success("分配角色成功")
      })
    }
  }
}
</script>

<style scoped>

</style>
